package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.*;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapSort;
import com.ruoyi.system.outto.core.constant.GameTypeConstant;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.NEWCYXAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author lz
 * @version 1.0
 * @date 2022/8/16 22:58
 */
@Slf4j
@Service
public class NEWCYXApiImpl implements NEWCYXAPI {

    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private AccountInfoMapper accountInfoMapper;
    @Resource
    private GoodsInfoMapper goodsInfoMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa) {
        Map<String, Object> resultMap = new HashMap<>();
        String url = sa.getThreeOther();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, sa);
        params = doneCommonParms(sa, params);
        String requestp = JSONObject.toJSONString(params);
        log.info("畅游星添加接口请求参数={}", requestp);
        String result = null;
        JSONObject json = JSONObject.parseObject(requestp);
        try {
            result = HttpUtils.sendPostJson(url + "?m=api&c=Archives&a=add", json, "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("畅游星添加接口返回参数={}", result);

        JSONObject resultJson = JSONObject.parseObject(result);
        String data = resultJson.getString("data");
        if (!"10000".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(sa.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(artRecs.size()>0) {
                artRecs.get(0).setOutid(JSONObject.parseObject(data).getString("account"));
                artRecMapper.updateArtRec(artRecs.get(0));
            }else{
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                artRecreq.setType(LCConstant.interAdd);
                artRecreq.setConfig(sa.getId());
                artRecreq.setSaleCode(sa.getSaleName());
                artRecreq.setOutid(JSONObject.parseObject(data).getString("account"));
                artRecMapper.insertArtRec(artRecreq);
            }
        }
        resultMap.put("req", requestp);
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.toJSONString());

        return AjaxResult.success(resultMap);
    }

//    private static AjaxResult getAjaxResult(Map<String, Object> resultMap, String requestp, String result) {
//
//    }

    /**
     * 公共参数
     *
     * @param sa
     */
    private Map<String, Object> doneCommonParms(SalePartner sa, Map<String, Object> params) {
        params.put("app_id", sa.getSaleKey());
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        List<Map.Entry<String, Object>> entries = new MapSort().sortMap(params);
        String key = sa.getOther();
        StringBuilder sb = new StringBuilder();
        HashMap<String, Object> newMap = new HashMap<>();

        for (final Map.Entry<String, Object> m : entries) {
            if (m.getValue() == null) {
                sb.append(m.getKey() + "=" + "1" + "&");
                newMap.put(m.getKey(), "1");
            } else {
                if (StringUtils.isEmpty(m.getValue().toString())) {
                    sb.append(m.getKey() + "=" + "1" + "&");
                    newMap.put(m.getKey(), "1");

                } else {
                    sb.append(m.getKey() + "=" + m.getValue().toString() + "&");
                    newMap.put(m.getKey(), m.getValue());
                }
            }

        }
        String substring = sb.substring(0, sb.length() - 1);
        newMap.put("sign", DigestUtils.md5Hex(substring + key));
        return newMap;
    }

    private SalePartner getSalePartner(Long userId) {
        SalePartner sa = commonApi.get(LCConstant.saleNameCYX, userId);
        if (Objects.isNull(sa)) {
            throw new GlobalException("合作伙伴未查到");
        }
        return sa;
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,  SalePartner sa) {
        Map<String, Object> resultMap = new HashMap<>();
        String url = sa.getThreeOther();
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, sa);
        params = doneCommonParms(sa, params);
        String requestp = JSONObject.toJSONString(params);
        log.info("畅游星编辑接口请求参数={}", requestp);
        String result = null;
        JSONObject json = JSONObject.parseObject(requestp);
        try {
            result = HttpUtils.sendPostJson(url + "?m=api&c=Archives&a=edit", json, "UTF-8");
            log.info("畅游星编辑接口返回参数={}", result);
        } catch (IOException e) {
            resultMap.put("req", requestp);
            resultMap.put("res", result);
            resultMap.put("msg", "未知");
            return AjaxResult.success(resultMap);
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"10000".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", requestp);
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.toJSONString());

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa) {
        Map<String, Object> resultMap = new HashMap<>();
        String url = sa.getThreeOther();
        Map<String, Object> params = new HashMap<>();
        params.put("p_number", String.valueOf(goodsInfoAndAttrValueDto.getId()));
        params = doneCommonParms(sa, params);
        String requestp = JSONObject.toJSONString(params);
        log.info("畅游星删除接口请求参数={}", requestp);
        String result = null;
        JSONObject json = JSONObject.parseObject(requestp);

        try {
            result = HttpUtils.sendPostJson(url + "?m=api&c=Archives&a=del", json, "UTF-8");
        } catch (IOException e) {
            resultMap.put("req", requestp);
            resultMap.put("res", result);
            resultMap.put("msg", "未知");
            return AjaxResult.success(resultMap);
        }

        log.info("畅游星删除接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"10000".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(sa.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(artRecs.size()>0) {
                artRecMapper.deleteArtRecById(artRecs.get(0).getId());
            }
        }
        resultMap.put("req", requestp);
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.toJSONString());

        return AjaxResult.success(resultMap);

    }


    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner sa) {

        Map<String, Object> params = new TreeMap<>();
        String gameType = goodsInfoAndAttrValueDto.getGameName();
        String title = goodsInfoAndAttrValueDto.getDes();
        Integer typeid = gamelCover(gameType);
        String regional = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
        if (typeid == null) {
            throw new GlobalException("游戏匹配失败，当前游戏:" + gameType + "，区服" + regional);
        }
        GameAttribute gameAttribute = null;
        if(Objects.equals("王者荣耀", goodsInfoAndAttrValueDto.getGameName())) {
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF16()));
        }
        if(Objects.equals("和平精英", goodsInfoAndAttrValueDto.getGameName())) {
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF10()));
        }
        if(goodsInfoAndAttrValueDto.getGameName().contains("原神")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF20()));
        }
        if(goodsInfoAndAttrValueDto.getGameName().contains("英雄联盟")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF1()));
        }
        if(goodsInfoAndAttrValueDto.getGameName().contains("穿越火线")){
            gameAttribute = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF3()));
        }
        params.put("typeid", typeid);
        Long id = goodsInfoAndAttrValueDto.getId();
        params.put("title", "【" + descTitle + "_" + id + "】 " +  gameAttribute.getFieldName() + title);
        params.put("small_title", "【" + descTitle + "_" + id + "】 " + gameAttribute.getFieldName() + title);
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,goodsInfoAndAttrValueDto.getId(),sa);
        params.put("price", String.valueOf(bigDecimal));
        params.put("daqu", regionalCover(gameType, regional));
        if (Objects.equals(99,typeid)){
            params.put("zhanqu", goodsInfoAndAttrValueDto.getGroupName());
            if ("有修改机会且实名是本人".contains(gameAttribute.getFieldName())){
                params.put("smbl", "可二次实名");
            }else {
                params.put("smbl", "可包人脸");
            }
            if(goodsInfoAndAttrValueDto.getServerName().contains("黑龙江")) {
                params.put("category_name", goodsInfoAndAttrValueDto.getServerName().substring(0, 3));
            }else if(goodsInfoAndAttrValueDto.getServerName().contains("大区")) {
                params.put("category_name", goodsInfoAndAttrValueDto.getServerName());
            }else{
                params.put("category_name", goodsInfoAndAttrValueDto.getServerName().substring(0, 2));
            }
            params.put("role_name", "可排位");
        }
        //图片
        StringBuilder imagesSb = new StringBuilder();
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        if (CollectionUtils.isEmpty(infoImgs)) {
        } else {
            for (GoodsInfoImg img : infoImgs) {
                imagesSb.append(img.getImgUrl()).append(",");
            }
        }
        params.put("image", StringUtils.isEmpty(imagesSb.toString()) ? "https://game.ikbh.top/logo/no_img.jpg" : imagesSb.toString());
        params.put("p_number", String.valueOf(id));
        params.put("content", title);
        return params;
    }


    private Integer regionalCover(String game, String regional) {
        if (Objects.equals("安卓QQ", regional)) {
            return 1;
        } else if (Objects.equals("安卓微信", regional)) {
            return 2;
        } else if (Objects.equals("苹果微信", regional)) {
            return 4;
        } else if (Objects.equals("苹果QQ", regional)) {
            return 3;
        } else {
            return 5;
        }
    }

    private Integer gamelCover(String game) {
        if (Objects.equals(GameTypeConstant.WZRY, game)) {
            return 75;
        }
        if (Objects.equals(GameTypeConstant.HPJY, game)) {
            return 89;
        }
        if (Objects.equals(GameTypeConstant.YS, game)) {
            return 95;
        }
        if (Objects.equals(GameTypeConstant.LOL, game)) {
            return 90;
        }
        if (Objects.equals(GameTypeConstant.NEWCF, game)) {
            return 99;
//        if (Objects.equals(GameTypeConstant.YJWJ, game)) {
//            return 90;
        } else {
            return null;
        }
    }

}
